﻿using System;
using System.Linq;
using System.Text;
using System.IO;
using Celeriq.Common;

namespace Celeriq.RepositoryAPI
{
    public class QueryLogger
    {
        private string _path;
        private object _locker = new object();

        public QueryLogger(string path)
        {
            if (!Directory.Exists(path))
            {
                throw new Exception("The path '" + path + "' does not exist!");
            }
            _path = Path.Combine(path, "QueryLogs");
            if (!Directory.Exists(_path))
                Directory.CreateDirectory(_path);
        }

        public void Log(DataQuery query, int elapsed, int count, bool fromcache)
        {
            lock (_locker)
            {
                var fileName = this.FileName;
                if (!File.Exists(fileName))
                {
                    var header = "#Software: Widgetsphere Celeriq Server\r\n" +
                                 "#Version: 2.0\r\n" +
                                 "#Date: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n" +
                                 "#Fields: date ip count time-taken cache queryid query\r\n";
                    File.AppendAllText(fileName, header);
                }

                var ipAddress = this.CallerAddress;
                if (!string.IsNullOrEmpty(query.IPMask))
                    ipAddress = query.IPMask;

                var line = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ff") + "\t" + ipAddress + "\t" + count + "\t" + elapsed + "\t" + (fromcache ? "1" : "0") + "\t" + query.QueryID + "\t" + query.ToString() + "\r\n";
                File.AppendAllText(fileName, line);
            }
        }

        private string FileName
        {
            get
            {
                var retval = DateTime.Now.ToString("yyyy-MM-dd");
                retval = Path.Combine(_path, retval) + ".query.log";
                return retval;
            }
        }

        private string CallerAddress
        {
            get
            {
                if (System.ServiceModel.OperationContext.Current != null)
                {
                    if (System.ServiceModel.OperationContext.Current.IncomingMessageProperties != null)
                    {
                        var o = System.ServiceModel.OperationContext.Current.IncomingMessageProperties["System.ServiceModel.Channels.RemoteEndpointMessageProperty"] as System.ServiceModel.Channels.RemoteEndpointMessageProperty;
                        if (o != null)
                        {
                            return o.Address;
                        }
                    }
                }
                return string.Empty;
            }
        }

    }
}